// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
import qrqrqr from '../../miniprogram_npm/weapp-qrcode/index'
Page({
    data: {
        indicatorDots: true, //小点
        indicatorColor: "white", //指示点颜色
        activeColor: "white", //当前选中的指示点颜色
        autoplay: false, //是否自动轮播
        interval: 3000, //间隔时间
        duration: 2000, //滑动时间
        navtop: "",
        Batterysvalue: "0%",
        currentTimeStamp: 0,
        num: [],
        openid: "",
        name: "",
        phone: "",
        id: "",
        jhr: [],
        sfz: "",
        age: "",
        imgurl: [],
        laoren: [],
        total_walk: "xx",
        device_code: "",
        diedao_alarm: '跌倒报警',
        jiuzuo_text: "未久坐",
        sbxx: "",
        index1: 0,
        show: [],
        dataLoaded: false,
        intervalId: null,
        is_subscribe:false
    },
    onLoad: function () {

    },

    onReady() {
        this.getnew();
    },

    onShow: function () {
        const that = this
        const app = getApp()
        app.fetchData().then(data => {
            // 数据请求成功，可以在这里进行页面加载操作
            that.setData({
                openid: app.globalData.openid
            }, function () {
                that.getdata1();
                that.getDate2();
                that.getnew();
            })
        })
        let currentTimeStamp = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0, 8)
        this.setData({
            currentTimeStamp: currentTimeStamp,
        });
        // 导航栏
        // 1.获取屏幕可使用宽度
        let windowWidth = wx.getSystemInfoSync().windowWidth;
        // 2.获取状态栏高度
        const statusBarHeight = wx.getSystemInfoSync().statusBarHeight;
        //3.获取胶囊按钮位置信息
        const menuButton = wx.getMenuButtonBoundingClientRect();
        this.setData({
            navtop: menuButton.top
        })
        this.setData({
            dataLoaded: false
        })
        wx.showToast({
            title: '加载中...',
            icon: 'loading',
            mask: true
        });
    },
    onHide() {
        this.setData({
            indicatorDots: true, //小点
            indicatorColor: "white", //指示点颜色
            activeColor: "white", //当前选中的指示点颜色
            autoplay: false, //是否自动轮播
            interval: 3000, //间隔时间
            duration: 2000, //滑动时间
            navtop: "",
            Batterysvalue: "0%",
            currentTimeStamp: 0,
            num: [],
            openid: "",
            name: "",
            phone: "",
            id: "",
            jhr: [],
            sfz: "",
            age: "",
            imgurl: [],
            laoren: [],
            total_walk: "xx",
            device_code: "",
            diedao_alarm: '跌倒报警',
            jiuzuo_text: "未久坐",
            sbxx: "",
            index1: 0,
            show: [],
            dataLoaded: false,
            intervalId: null,
        })
        if (this.data.intervalId) {
            clearInterval(this.data.intervalId);
            console.log('定时器被删除');
        }

    },

    getinfo(e) {
        const itemId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '../detali/detali?id=' + itemId
        })
    },
    bangding() {
        wx.navigateTo({
            url: '../oldcard/oldcard',
        })
    },
    bangding2() {
        wx.navigateTo({
            url: '../user/user',
        })
    },
    getdata1() {
        const that = this
        const app = getApp()
        this.setData({
            openid: app.globalData.openid,
        })
        wx.request({
            url: 'https://dj.ifankui.com/api/usrEn/getProfile',
            method: "POST",
            data: {
                openid: this.data.openid
            },
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            success: (res) => {
                console.log(res);
                console.log(res.data.data.jhr, );
                this.setData({
                    name: res.data.data.realname,
                    phone: res.data.data.mobile,
                    id: res.data.data.id,
                    laoren: res.data.data.laoren,
                    sfz: res.data.data.sfz,
                    is_subscribe:res.data.data.is_subscribe
                }, function () {
                    const laoren11 = that.data.laoren;
                    that.data.laoren.forEach(pp => {
                        let birthYear = parseInt(pp.sfz.substring(6, 10));
                        let birthMonth = parseInt(pp.sfz.substring(10, 12));
                        let birthDay = parseInt(pp.sfz.substring(12, 14));

                        // 获取当前日期
                        let today = new Date();
                        let currentYear = today.getFullYear();
                        let currentMonth = today.getMonth() + 1;
                        let currentDay = today.getDate();
                        // 计算年龄
                        let birthDate = new Date(birthYear, birthMonth - 1, birthDay);
                        let age = currentYear - birthYear;

                        // 调整年龄，如果当前月份和日期还没到生日，则减一岁
                        if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
                            age--;
                        }
                        that.setData({
                            ['laoren[' + that.data.laoren.indexOf(pp) + '].age']: age
                        }, () => {
                            console.log(that.data.laoren);
                        })

                    });

                })
                // 提取出生年月日

            }
        })
    },
    getnew() {
        const that = this;
        wx.request({
            url: 'https://dj.ifankui.com/api/notice/index',
            success(res) {
                console.log(res);
                const p = res.data.notice
                console.log(p.length);
                for (let i = 0; i < p.length; i++) {
                    p[i].dt = p[i].dt.slice(0, p[i].dt.length - 8)
                }
                console.log(p);
                that.setData({
                    num: p
                })

            }
        })
        wx.request({
            url: 'https://dj.ifankui.com/api/home/index',
            success(res) {
                console.log(res);
                that.setData({
                    imgurl: res.data.homeSwiper
                })
            }
        })
    },
    callphone: function (e) {
        console.log(e.currentTarget.dataset.phone);
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone, // 这里填写要拨打的电话号码
            success: function () {
                console.log("拨打电话成功！")
            },
            fail: function () {
                console.log("拨打电话失败！")
            }
        })
    },
    getDate2() {
        const that = this
        const app = getApp()
        this.setData({
            openid: app.globalData.openid
        })
        console.log(app.globalData.openid);
        wx.request({
            url: 'https://dj.ifankui.com/api/usrEn/deviceList',
            method: "POST",
            data: {
                openid: this.data.openid
            },
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            success: (res) => {
                if (!res.data.data[0]) {
                    this.setData({
                        dataLoaded: true
                    })
                    return
                }
                console.log(res);
                let p = []
                let p1 = []
                const a = res.data.data
                a.forEach(element => {
                    p.push(element)
                    p1.push(element.device_code)
                });
                this.setData({
                    sbxx: p,
                    show: p1,
                    sfz: res.data.data[that.data.index1].sfz
                }, () => {
                    that.generateQRCode(this.data.sbxx[that.data.index1].device_code + "," + that.data.sfz, 'myQrCodeCanvas');
                    wx.request({
                        url: 'https://dj.ifankui.com/api/device/getDeviceInfo',
                        method: "POST",
                        data: {
                            openid: this.data.openid,
                            // device_code:"898604B0102140204004",
                            device_code: this.data.sbxx[that.data.index1].device_code,
                        },
                        header: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        },
                        success: (res) => {
                            console.log(res);
                            let ppp = {}
                            console.log(res.data.device.jiuzuo_alarm[0]);
                            if (!res.data.device.jiuzuo_alarm[0]) {
                                ppp = 1
                            } else {
                                ppp = res.data.device.jiuzuo_alarm[0];
                            }
                            let batterys = res.data.device.battery
                            this.setData({
                                Batterysvalue: batterys,
                                device_code: res.data.device.device_code,
                                total_walk: res.data.device.total_walk,
                                diedao_alarm: res.data.device.diedao_alarm,
                                jiuzuo_alarm: ppp,
                                dataLoaded: true
                            }, () => {
                                const inputDate = that.data.jiuzuo_alarm.dt
                                console.log(that.data);

                                function inputDate11(inputDate) {
                                    if (inputDate) {
                                        let inputDate1 = inputDate.replace(/-/g, '/');
                                        return inputDate1
                                    } else {
                                        let inputDate1 = ""
                                        return inputDate1
                                    }
                                }
                                let inputDate1 = inputDate11(inputDate)
                                const date = new Date(inputDate1);
                                // 获取当前时间
                                const now = new Date();
                                console.log(now, date);
                                // 计算时间差（单位：毫秒）
                                const diffInMillis = now - date;
                                // 将毫秒转换为分钟
                                const diffInMinutes = Math.floor(diffInMillis / (1000 * 60));
                                // 计算小时数
                                const hours = Math.floor(diffInMinutes / 60);
                                // 计算剩余分钟数
                                const minutes = diffInMinutes % 60;
                                that.setData({
                                    jiuzuo_text: hours + "小时" + minutes + "分" + "前"
                                })
                                console.log(res.data.device.battery.slice(0,-1));
                                let percentageNumber = parseFloat(res.data.device.battery.slice(0,-1));
                                console.log(percentageNumber);
                                if (percentageNumber < 20) {
                                    wx.showModal({
                                        title: '警告',
                                        content: '当前电量低于20%',
                                        showCancel: false, // 是否显示取消按钮
                                        confirmText: '确定', // 确定按钮的文字
                                        confirmColor: '#fb3660', // 确定按钮的文字颜色
                                        success: function (res) {
                                            if (res.confirm) {
                                                console.log('用户点击确定');
                                                // 用户点击确定后的操作
                                            } else if (res.cancel) {
                                                console.log('用户点击取消');
                                                // 用户点击取消后的操作
                                            }
                                        }
                                    });
                                }
                            })
                        }
                    })
                    this.getDate3()
                })
            }
        })
    },
    getDate3() {
        if (this.data.intervalId) {
            clearInterval(this.data.intervalId);
            console.log('定时器被删除');
        }
        this.data.intervalId = setInterval(() => {
            console.log(this.data.sbxx);
            wx.request({
                url: 'https://dj.ifankui.com/api/device/getDeviceInfo',
                method: "POST",
                data: {
                    openid: this.data.openid,
                    device_code: this.data.sbxx[this.data.index1].device_code,
                },
                header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                success: (res) => {
                    console.log(res);
                    let ppp = {}
                    console.log(res.data.device.jiuzuo_alarm[0]);
                    if (!res.data.device.jiuzuo_alarm[0]) {
                        ppp = 1
                    } else {
                        ppp = res.data.device.jiuzuo_alarm[0];
                    }
                    let batterys = res.data.device.battery

                    this.setData({
                        Batterysvalue: batterys,
                        device_code: res.data.device.device_code,
                        total_walk: res.data.device.total_walk,
                        diedao_alarm: res.data.device.diedao_alarm,
                        jiuzuo_alarm: ppp,
                        dataLoaded: true
                    })

                }
            })
        }, 10000);
        const inputDate = this.data.jiuzuo_alarm.dt
        console.log(inputDate);
        // console.log(jiuzuo_alarm.length);

        function inputDate11(inputDate) {
            if (inputDate) {
                let inputDate1 = inputDate.replace(/-/g, '/');
                return inputDate1
            } else {
                let inputDate1 = ""
                return inputDate1
            }
        }
        let inputDate1 = inputDate11(inputDate)
        const date = new Date(inputDate1);
        // 获取当前时间
        const now = new Date();
        console.log(now, date);
        // 计算时间差（单位：毫秒）
        const diffInMillis = now - date;
        // 将毫秒转换为分钟
        const diffInMinutes = Math.floor(diffInMillis / (1000 * 60));
        // 计算小时数
        const hours = Math.floor(diffInMinutes / 60);
        // 计算剩余分钟数
        const minutes = diffInMinutes % 60;
        this.setData({
            jiuzuo_text: hours + "小时" + minutes + "分" + "前"
        })
        // let percentageNumber = parseFloat(res.data.device.jiuzuo_alarm[0].battery.slice(0,-1));
        // if (percentageNumber < 20) {
        //     wx.showModal({
        //         title: '警告',
        //         content: '当前电量低于20%',
        //         showCancel: false, // 是否显示取消按钮
        //         confirmText: '确定', // 确定按钮的文字
        //         confirmColor: '#fb3660', // 确定按钮的文字颜色
        //         success: function (res) {
        //             if (res.confirm) {
        //                 console.log('用户点击确定');
        //                 // 用户点击确定后的操作
        //             } else if (res.cancel) {
        //                 console.log('用户点击取消');
        //                 // 用户点击取消后的操作
        //             }
        //         }
        //     });
        // }
    },
    stopDate3() {
        if (this.data.intervalId) {
            clearInterval(this.data.intervalId); // 清除定时器
            this.data.intervalId = null; // 清空定时器ID
            console.log("定时器已停止");
        }
    },
    showActionSheet() {
        const that = this
        wx.showActionSheet({
            itemList: that.data.show,
            success(res) {
                console.log(res.tapIndex) // 用户点击的按钮序号，从0开始
                that.setData({
                    index1: res.tapIndex,
                })
                that.getDate2()
            },
            fail(res) {
                console.log(res.errMsg)
            }
        })
    },
    generateQRCode(text, canvasId) {
        console.log(text);
        try {
            const qrcode = new qrqrqr({
                canvasId: 'myQrCanvas',
                text: text,
                width: 275,
                height: 275,
            });
            console.log('QR code generated successfully.');
        } catch (error) {
            console.error('Error generating QR code:', error);
        }
    },
    // 授权
    // authorizationBtn() {
    //     wx.requestSubscribeMessage({
    //         tmplIds: ['Tt5fOjdvFQGvdnuUo-SlG_Nnqre2QYGrPcbEoSC21NA'],
    //         success(res) {
    //             console.log('授权成功')
    //         }
    //     })
    // },
    openMsg(){
        wx.navigateTo({
          url: '../guanzhu/guanzhu?mini_openid=' + getApp().globalData.openid,
        })
    },
    // openMsg() {
    //     const _this = this;
    //     // 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
    //     wx.getSetting({
    //         withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
    //         success(res) {
    //             console.log('res.authSetting', res.authSetting)
    //             if (res.authSetting['scope.subscribeMessage']) {
    //                 console.log('用户点击了“总是保持以上，不再询问”')

    //             } else {
    //                 console.log('用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息')
    //                 //因为没有选择总是保持，所以需要调起授权弹窗再次授权
    //                 _this.authorizationBtn();
    //                 wx.showModal({
    //                     title: '已开启警报',
    //                     showCancel: false, // 不显示取消按钮
    //                     success: function (res) {
    //                         if (res.confirm) {
    //                             console.log('用户点击确定');
    //                         }
    //                     }
    //                 });
    //             }
    //         }
    //     })
    // }



})